package cc.c3p0.admin.module.menu.service.impl;

import cc.c3p0.admin.common.dto.Tree;
import cc.c3p0.admin.common.mapper.BasicMapper;
import cc.c3p0.admin.common.service.impl.BasicServiceImpl;
import cc.c3p0.admin.module.menu.service.MenuServiceI;
import cc.c3p0.admin.module.menu.vo.MenuTreeVO;
import cc.c3p0.admin.mybatis.mapper.AdminMenuMapper;
import cc.c3p0.admin.mybatis.model.AdminMenu;
import cc.c3p0.admin.mybatis.model.AdminUser;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单管理业务实现
 * Created by binchao on 2017/4/9.
 */
@Service
public class MenuServiceImpl extends BasicServiceImpl<AdminMenu>
    implements MenuServiceI {

    @Resource
    private AdminMenuMapper menuMapper;

    @Override
    protected BasicMapper<AdminMenu> getMapper() {
        return menuMapper;
    }

    @Override
    public List<MenuTreeVO> getMenuTree(String sid) {
        List<MenuTreeVO> list = new ArrayList<>();
        // TODO 先查出用户组 拥有的菜单ids
        String ids = "";
        // 再根据 系统id，菜单ids查出 相应的菜单信息
        Map<String, Object> params = new HashMap<>();
        params.put("sid", sid);
        params.put("ids", ids);
        List<AdminMenu> menuList = menuMapper.getMenuInfo(params);
        // 再根据查询出来的菜单，构造菜单树。
        for (AdminMenu pMenu : menuList) {
            if (pMenu.getIsparent()) {
                MenuTreeVO root = new MenuTreeVO();
                BeanUtils.copyProperties(pMenu, root);
                List<MenuTreeVO> subMenuList = new ArrayList<>();
                for (AdminMenu subMenu: menuList) {
                    if (subMenu.getPid().equals(pMenu.getId())) {
                        MenuTreeVO node = new MenuTreeVO();
                        BeanUtils.copyProperties(subMenu, node);
                        subMenuList.add(node);
                    }
                }
                root.setSubMenu(subMenuList);
                list.add(root);
            }
        }

        return list;
    }

    @Override
    public List<Tree> getCTree() {
        List<Tree> tree = menuMapper.selectMenuTree();
        // 获取当前用户所属用户组
//        if (null != user && null != user.getGids()) {
//            String gids = user.getGids();
//            List<AdminGroup> groups = groupMapper.selectList(gids.split(","));
//            for (AdminGroup g : groups) {
//
//            }
//        }
        return tree;
    }
}
